##
# Show status of MySQL
# @param $1 install home
# @param $2 delimiter
# @param $3 host
# @param $4 port
# @param $5 username
# @param $6 password
#
use strict;
#my $SQL = "show global variables where variable_name in ('datadir','innodb_data_home_dir','innodb_data_file_path');"
my $SQL = "show global variables like 'datadir'; show global variables like 'innodb_data_home_dir'; show global variables like 'innodb_data_file_path';";
my ($MYSQL_HOME,$DELIM,$HOST,$PORT,$USER,$PASS) = @ARGV;
my $PARAM="";
$PARAM="$PARAM -h\"$HOST\"" if (defined($HOST) && $HOST ne "");
$PARAM="$PARAM -P\"$PORT\"" if (defined($PORT) && $PORT ne "");
$PARAM="$PARAM -u\"$USER\"" if (defined($USER) && $USER ne "");
$PARAM="$PARAM -p\"$PASS\"" if (defined($PASS) && $PASS ne "");
my $MYSQL="$MYSQL_HOME/bin/mysql";
my $MYSQLADMIN="$MYSQL_HOME/bin/mysqladmin";
my $PATHCHR = '/';
if ($^O =~ m/MSWin32/) {
  $MYSQL =~ s/\//\\/g;
  $MYSQLADMIN =~ s/\//\\/g;
  $PATHCHR = '\\';
}
# Check if mysqld is alive
my $retmsg=`$MYSQLADMIN $PARAM ping 2>&1`;
chomp($retmsg);
if ( "$retmsg" ne "mysqld is alive" ) {
    print "em_error=Status${DELIM}Down\n";
    exit 1;
}
# Execute command and display the result as key-value pairs
my @KV=`$MYSQL -N -s $PARAM -e"$SQL"`;
chomp(@KV);
my %hash = ();
for (@KV) {
    my ($key, $value) = split /\t/, $_;
    $hash{$key} = $value;
}
# Get ibdata file name
my @ibdata_cfg = split /;/, $hash{'innodb_data_file_path'};
my @ibdatas;
for (@ibdata_cfg) {
    my @a = split /:/, $_;
    push @ibdatas, $a[0];
}
# Get and printf ibdata file size
for (@ibdatas) {
    my $filename = "";
    my $filesize = -1;
    my $path = "";
    if ( rindex($_, $PATHCHR) > -1 ) {
        $filename = $_;
    } elsif ( $hash{'innodb_data_home_dir'} ne "" ) {
        $path = $hash{'innodb_data_home_dir'};
    } elsif ( $hash{'datadir'} ne "" ) {
        $path = $hash{'datadir'};
    }
    if ($path ne "") {
        if (substr($path, length($path)-1) eq $PATHCHR) {
            $filename = $path.$_;
        } else {
            $filename = $path.$PATHCHR.$_;
        }
    }
    if ( -e "$filename" ) {
        $filesize = -s "$filename";
    }
    print "em_result=${filename}${DELIM}${filesize}\n";
}
exit 0;

